/**
 * 段落生成面板
 * 用于批量生成段落并选择版本
 */

import React, { useState, useEffect } from 'react';
import { Button, Progress, Space, Select, InputNumber, Card, message, Statistic, Row, Col } from 'antd';
import {
  PlayCircleOutlined,
  PauseOutlined,
  StopOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { useParagraphStore } from '@/stores/paragraph.store';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import { ParagraphStrategy } from '@/types/brainstorm';
import { VersionCompare } from '../VersionCompare';
import './style.css';

const { Option } = Select;

export const ParagraphGenerationPanel: React.FC = () => {
  const { currentSession } = useBrainstormStore();
  const {
    paragraphs,
    currentNodeId,
    generating,
    paused,
    currentProgress,
    startGeneration,
    pauseGeneration,
    resumeGeneration,
    stopGeneration,
    selectVersion,
    regenerateVersion,
    mixVersions,
  } = useParagraphStore();

  const [versionCount, setVersionCount] = useState(3);
  const [strategies, setStrategies] = useState<ParagraphStrategy[]>([
    'concise',
    'detailed',
    'vivid',
  ]);

  const currentParagraph = currentNodeId ? paragraphs[currentNodeId] : null;
  const completedCount = Object.keys(paragraphs).filter((key) => {
    const p = paragraphs[key];
    return p.selectedVersionIndex >= 0 && !p.versions[p.selectedVersionIndex]?.generating;
  }).length;

  const totalCount = currentSession?.outline?.nodes.length || 0;

  // 开始生成
  const handleStart = async () => {
    if (!currentSession?.outline) {
      message.error('请先创建大纲');
      return;
    }

    if (strategies.length < versionCount) {
      message.error('请选择足够的策略');
      return;
    }

    await startGeneration(versionCount, strategies);
  };

  return (
    <div className="paragraph-generation-panel">
      {/* 顶部标题 */}
      <div className="panel-header">
        <h2>正文段落生成</h2>
        <p className="panel-subtitle">
          AI智能生成多个版本的段落内容，您可以选择最满意的版本
        </p>
      </div>

      {/* 统计信息 */}
      <Card className="stats-card" bordered={false}>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="总段落数"
              value={totalCount}
              prefix={<CheckCircleOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="已完成"
              value={completedCount}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="进行中"
              value={generating ? 1 : 0}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="完成率"
              value={totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0}
              suffix="%"
            />
          </Col>
        </Row>
      </Card>

      {/* 控制面板 */}
      <Card title="生成设置" bordered={false} className="control-card">
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          {/* 版本数量 */}
          <div className="control-item">
            <label className="control-label">版本数量:</label>
            <InputNumber
              min={2}
              max={4}
              value={versionCount}
              onChange={(val) => setVersionCount(val || 2)}
              disabled={generating}
              style={{ width: 120 }}
              addonAfter="个"
            />
            <span className="control-desc">每个段落生成多个版本</span>
          </div>

          {/* 生成策略 */}
          <div className="control-item">
            <label className="control-label">生成策略:</label>
            <Select
              mode="multiple"
              style={{ flex: 1, maxWidth: 500 }}
              value={strategies}
              onChange={setStrategies}
              disabled={generating}
              placeholder="选择生成策略"
            >
              <Option value="concise">简洁风格 - 150-200字，直入主题</Option>
              <Option value="detailed">详细风格 - 300-400字，深入阐述</Option>
              <Option value="vivid">生动风格 - 使用比喻和案例</Option>
              <Option value="data-driven">数据风格 - 使用数据和图表</Option>
            </Select>
          </div>

          {/* 操作按钮 */}
          <Space>
            {!generating ? (
              <Button
                type="primary"
                size="large"
                icon={<PlayCircleOutlined />}
                onClick={handleStart}
                disabled={!currentSession?.outline}
              >
                开始生成
              </Button>
            ) : paused ? (
              <Button
                type="primary"
                size="large"
                icon={<PlayCircleOutlined />}
                onClick={resumeGeneration}
              >
                继续
              </Button>
            ) : (
              <Button
                size="large"
                icon={<PauseOutlined />}
                onClick={pauseGeneration}
              >
                暂停
              </Button>
            )}

            {generating && (
              <Button
                size="large"
                danger
                icon={<StopOutlined />}
                onClick={stopGeneration}
              >
                停止
              </Button>
            )}
          </Space>
        </Space>
      </Card>

      {/* 进度条 */}
      {generating && (
        <Card className="progress-card" bordered={false}>
          <div className="progress-info">
            <span className="progress-label">总体进度:</span>
            <span className="progress-text">
              {completedCount}/{totalCount} 段落
            </span>
          </div>
          <Progress
            percent={currentProgress}
            status={paused ? 'exception' : 'active'}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
          {currentNodeId && (
            <div className="current-task">
              <span>当前: {currentNodeId}</span>
            </div>
          )}
        </Card>
      )}

      {/* 当前段落版本对比 - 批量生成时显示所有段落 */}
      {Object.keys(paragraphs).length > 0 && (
        <div className="all-paragraphs-container">
          {Object.entries(paragraphs).map(([nodeId, paragraph]) => (
            <Card
              key={nodeId}
              title={`段落: ${nodeId} ${nodeId === currentNodeId ? '(生成中...)' : ''}`}
              bordered={false}
              className={`paragraph-card ${nodeId === currentNodeId ? 'current-paragraph' : ''}`}
              style={{ marginBottom: 16 }}
            >
              <VersionCompare
                versions={paragraph.versions}
                selectedVersionIndex={paragraph.selectedVersionIndex}
                onSelectVersion={(index) => {
                  selectVersion(nodeId, index);
                  message.success('版本已选择');
                }}
                onRegenerateVersion={async (index) => {
                  await regenerateVersion(nodeId, index);
                }}
                onMixVersions={async (selections) => {
                  await mixVersions(nodeId, selections);
                }}
              />
            </Card>
          ))}
        </div>
      )}

      {/* 空状态 */}
      {!generating && !currentParagraph && Object.keys(paragraphs).length === 0 && (
        <Card className="empty-state">
          <div className="empty-content">
            <h3>暂无生成的段落内容</h3>
            <p>点击"开始生成"按钮，AI将为您批量生成段落内容</p>
            <p className="empty-hint">提示：可以先设置版本数量和生成策略，然后点击开始生成按钮</p>
          </div>
        </Card>
      )}
    </div>
  );
};
